﻿using Microsoft.AspNetCore.Mvc;
using WebHome_API.Models;
using WebHome_API.Models.DataModels;
using WebHome_API.Models.DBModels;
using WebHome_API.Models.OperResult;
using WebHome_API.Tools;

namespace WebHome_API.Controllers
{
    [Route("api/[controller]")]
    [Controller]
    public class NovelController : ControllerBase
    {
        [HttpGet("getNovelOfIndexof")]
        public OperResult<NovelInfoList> getNovelOfIndexof(string text, int page = 1)
        {
            if (string.IsNullOrEmpty(text))
            {
                return OperResult<NovelInfoList>.Failed($"请指定通配符数据");
            }
            int curCount = 20;
            int curPage = 1;
            if (page <= 0)
                curPage = 1;
            else
                curPage = page;
            using (MyContext context = new())
            {
                var list = context.Novels
                     .Where(u => u.IsDel == 0)
                     .Where(u => u.Name.ToLower().IndexOf(text) != -1)
                     .ToList();

                List<NovelInfo> ret = new();
                foreach (var item in list.Skip((curPage - 1) * curCount).Take(curCount))
                {
                    var filecount = context.FilePaths.Where(u => u.IsDel == 0 && u.FileType == (int)FileTypeEnum.Novel && u.FileId == item.ID).ToList().Count();
                    ret.Add(new NovelInfo()
                    {
                        Name = item.Name,
                        ID = item.ID,
                        FileCount = filecount,
                    });
                }
                int curMaxCount = list.Count;
                int curMaxPage = curMaxCount % curCount == 0 ? curMaxCount / curCount : curMaxCount % curCount + 1;
                return OperResult<NovelInfoList>.Succeed(new NovelInfoList()
                {
                    NovelInfos = ret,
                    Count = curCount,
                    MaxCount = curMaxCount,
                    Page = curPage,
                    MaxPage = curMaxPage,
                });
            }
        }

        [HttpGet("getNovelInfoOfID")]
        public OperResult<NovelInfo> getNovelInfoOfID(string id)
        {
            if (string.IsNullOrEmpty(id) || !int.TryParse(id, out int curId))
            {
                return OperResult<NovelInfo>.Failed($"没有找到[{id}]的数据");
            }
            using (MyContext context = new())
            {
                var novel = context.Novels.FirstOrDefault(u => u.ID == curId && u.IsDel == 0);
                if (novel == null)
                {
                    return OperResult<NovelInfo>.Failed($"没有找到[{curId}]的数据");
                }
                var files = context.FilePaths.Where(u => u.FileId == curId && u.FileType == (int)FileTypeEnum.Novel).ToList();
                var url = context.OtherEnums.FirstOrDefault(u => u.ID == 1)!.Text;
                //处理files
                Dictionary<string, List<string>> fileDict = new();
                foreach (var item in files)
                {
                    var temp = item.Path.Replace($"\\Novel\\{novel.Name}\\", "");
                    var arr = temp.Split('\\');
                    if (arr.Length >= 2)
                    {
                        if (fileDict.ContainsKey(arr[arr.Length - 2]))
                            fileDict[arr[arr.Length - 2]].Add(url + item.Path.Replace("\\", "/").TrimStart('/'));
                        else
                            fileDict[arr[arr.Length - 2]] = new List<string>() { url + item.Path.Replace("\\", "/").TrimStart('/') };
                    }
                    else
                    {
                        if (fileDict.ContainsKey("default"))
                            fileDict["default"].Add(url + item.Path.Replace("\\", "/").TrimStart('/'));
                        else
                            fileDict["default"] = new List<string>() { url + item.Path.Replace("\\", "/").TrimStart('/') };
                    }
                }


                var novelInfo = new NovelInfo()
                {
                    ID = novel.ID,
                    Name = novel.Name,
                    Files = fileDict
                };
                return OperResult<NovelInfo>.Succeed(novelInfo);
            }
        }

        [HttpGet("getNovelOfFirstE")]
        public OperResult<NovelInfoList> getNovelOfFirstE(string firstE, int page = 1)
        {
            if (string.IsNullOrEmpty(firstE) || firstE.Length != 1)
            {
                return OperResult<NovelInfoList>.Failed($"请指定通配符数据");
            }
            int curCount = 20;
            int curPage = 1;
            if (page <= 0)
                curPage = 1;
            else
                curPage = page;
            using (MyContext context = new())
            {
                var list = context.Novels
                     .Where(u => u.IsDel == 0)
                     .Where(u => u.FirstE == firstE)
                     .ToList();

                List<NovelInfo> ret = new();
                foreach (var item in list.Skip((curPage - 1) * curCount).Take(curCount))
                {
                    var filecount = context.FilePaths.Where(u=>u.IsDel == 0&& u.FileType == (int)FileTypeEnum.Novel && u.FileId == item.ID).ToList().Count();
                    ret.Add(new NovelInfo()
                    {
                        Name = item.Name,
                        ID = item.ID,
                        FileCount = filecount,
                    });
                }
                int curMaxCount = list.Count;
                int curMaxPage = curMaxCount % curCount == 0 ? curMaxCount / curCount : curMaxCount % curCount + 1;
                return OperResult<NovelInfoList>.Succeed(new NovelInfoList()
                {
                    NovelInfos = ret,
                    Count = ret.Count,
                    MaxCount = list.Count,
                    Page = curPage,
                    MaxPage = curMaxPage,
                });
            }
        }

        [HttpGet("setFirstE")]
        public void setFirstE()
        {
            using (MyContext context = new())
            {
                var list = context.Novels.Where(u => true).ToList();
                for (int i = 0; i < list.Count; i++)
                {
                    string temp = CNTool.GetFirstPinyin(list[i].Name)!;
                    if (int.TryParse(temp, out int j))
                    {
                        temp = "*";
                    }
                    list[i].FirstE = temp;
                }
                context.SaveChanges();
            }
        }



        [HttpGet("getNovelList")]
        public OperResult<NovelList> getNovelList(string tagId, string text, int page = 1, int perPage = 20)
        {
            //包含查询
            NovelList data;
            using (MyContext context = new())
            {
                List<Novel_Table> allList = context.Novels.OrderByDescending(u => u.LastUpdateTime).ToList();

                if (string.IsNullOrEmpty(text) && string.IsNullOrEmpty(tagId))
                {
                    data = new(allList, page, perPage, context);
                }
                else
                {
                    Dictionary<int, Novel_Table> ret = new();
                    //匹配Tag
                    if (!string.IsNullOrEmpty(tagId))
                    {
                        var arr = tagId.Split(',');

                        List<int> listOfTag = new();
                        foreach (var item in arr)
                        {
                            var galTag = context.FileTags.FirstOrDefault(u => u.ID == Convert.ToInt32(item));
                            if (galTag != null)
                            {
                                if (galTag.TagEnumID == (int)GalTagEnum.traits)
                                    listOfTag.Add(galTag.ID);
                            }
                        }

                        //后查特征
                        //查询拥有这些tag的taglink
                        if (listOfTag.Count != 0)
                        {
                            var tampTagLink = new List<FileTagLink_Table>();
                            //先查TapLink
                            listOfTag.ForEach(u =>
                            {
                                var temp = context.FileTagLink.Where(p => p.TagID == u && p.FileType == FileTypeEnum.Novel).ToList();
                                if (temp.Count != 0)
                                    tampTagLink.AddRange(temp);
                            });
                            //对TagLink查找的Gal进行去重
                            foreach (var item in tampTagLink)
                            {
                                if (!ret.ContainsKey(item.FileID))
                                {
                                    var tempGal = allList.FirstOrDefault(u => u.ID == item.FileID);
                                    if (tempGal != null)
                                        ret[item.FileID] = tempGal;
                                }
                            }
                        }
                    }

                    //最后模糊匹配
                    if (!string.IsNullOrEmpty(text))
                    {
                        var textArr = text.Split(',');

                        foreach (var item in textArr)
                        {
                            var curText = item.Trim().ToLower();
                            allList.Where(u =>
                                u.Name.ToLower().IndexOf(curText) != -1
                            ).ToList().ForEach(u =>
                            {
                                ret[u.ID] = u;
                            });
                        }
                    }
                    data = new NovelList(ret.Values.ToList(), page, perPage, context);
                }
            }

            return OperResult<NovelList>.Succeed(data);
        }

        [HttpGet("getNovelInfo")]
        public OperResult<NovelInfo> getNovelInfo(int id = 0)
        {
            using (MyContext context = new())
            {
                var novel = context.Novels.FirstOrDefault(u => u.ID == id && u.IsDel == 0);
                if (novel == null)
                {
                    return OperResult<NovelInfo>.Failed($"没有找到[id={id}]的数据");
                }
                var files = context.FilePaths.Where(u => u.FileId == novel.ID && u.FileType == (int)FileTypeEnum.Novel).ToList();
                var url = context.OtherEnums.FirstOrDefault(u => u.ID == 1)!.Text;
                //处理files
                Dictionary<string, List<string>> fileDict = new();
                foreach (var item in files)
                {
                    var temp = item.Path.Replace($"\\{novel.Name}\\", "");
                    var arr = temp.Split('\\');
                    if (arr.Length >= 2)
                    {
                        if (fileDict.ContainsKey(arr[arr.Length - 2]))
                            fileDict[arr[arr.Length - 2]].Add(url + item.Path.Replace("\\", "/").TrimStart('/'));
                        else
                            fileDict[arr[arr.Length - 2]] = new List<string>() { url + item.Path.Replace("\\", "/").TrimStart('/') };
                    }
                    else
                    {
                        if (fileDict.ContainsKey(novel.Name))
                            fileDict[novel.Name].Add(url + item.Path.Replace("\\", "/").TrimStart('/'));
                        else
                            fileDict[novel.Name] = new List<string>() { url + item.Path.Replace("\\", "/").TrimStart('/') };
                    }
                }
                //处理Tag
                Dictionary<int, FileTag_Table> tagDict = new();
                context.FileTagLink.Where(u => u.FileID == novel.ID && u.FileType == FileTypeEnum.Novel).ToList().ForEach(u =>
                {
                    var tag = context.FileTags.FirstOrDefault(o => o.ID == u.TagID);
                    if (tag != null)
                        tagDict[u.TagID] = tag;
                });

                var novelInfo = new NovelInfo()
                {
                    ID = novel.ID,
                    Name = novel.Name,
                    Category = novel.Category,
                    BackImage = url,
                    Files = fileDict,
                    Tags = tagDict.Values.ToList(),
                };
                return OperResult<NovelInfo>.Succeed(novelInfo);
            }
        }

    }
}
